import React, { useEffect, useState } from 'react';
import { Routes, Route, useLocation, useNavigate } from 'react-router-dom';
import { message, Spin } from 'antd';
import { usePermission } from '@/hooks/usePermission';
import { generateRoutes, hasRoutePermission } from '@/utils/dynamicRoutes';
import { useAuthStore } from '@/store/auth';
import MainLayout from '@/components/layout/MainLayout';
import NotFoundPage from '@/pages/error/NotFoundPage';
import type { RouteObject } from 'react-router-dom';

interface DynamicRouteGuardProps {
  basicRoutes: React.ReactElement;
  protectedRoutes: React.ReactElement;
}

const DynamicRouteGuard: React.FC<DynamicRouteGuardProps> = ({ basicRoutes, protectedRoutes }) => {
  const { permissionData, permissionLoading, getUserMenus, getUserPermissions } = usePermission();
  const { isAuthenticated, clearAuth } = useAuthStore();
  const location = useLocation();
  const navigate = useNavigate();
  const [dynamicRoutes, setDynamicRoutes] = useState<RouteObject[]>([]);

  useEffect(() => {
    console.log('[DynamicRouteGuard] permissionData 变化:', permissionData);
    if (permissionData) {
      // 根据用户权限生成动态路由
      const userMenus = getUserMenus();
      const userPermissions = getUserPermissions();

      console.log('[DynamicRouteGuard] 用户菜单:', userMenus);
      console.log('[DynamicRouteGuard] 用户权限:', userPermissions);

      if (!userMenus || userMenus.length === 0) {
        console.warn('[DynamicRouteGuard] 警告: 用户菜单数据为空!');
      }

      const routes = generateRoutes(userMenus);
      console.log('[DynamicRouteGuard] 生成的路由:', routes);

      // 过滤掉用户没有权限的路由
      const filteredRoutes = routes.filter(route =>
        hasRoutePermission(route, userPermissions)
      );

      console.log('[DynamicRouteGuard] 过滤后的路由:', filteredRoutes);
      setDynamicRoutes(filteredRoutes);
    }
  }, [permissionData]);

  useEffect(() => {
    // 检查当前路由是否需要权限
    if (permissionData && dynamicRoutes.length > 0) {
      const currentPath = location.pathname;
      const userPermissions = getUserPermissions();
      const userMenus = getUserMenus();

      console.log('[DynamicRouteGuard] 当前路径:', currentPath);
      console.log('[DynamicRouteGuard] 动态路由列表:', dynamicRoutes);

      // 查找当前路由配置
      const currentRoute = dynamicRoutes.find(route => route.path === currentPath);

      console.log('[DynamicRouteGuard] 找到的路由配置:', currentRoute);

      if (currentRoute) {
        // 检查权限
        const hasAccess = hasRoutePermission(currentRoute, userPermissions);
        console.log('[DynamicRouteGuard] 权限检查结果:', hasAccess);

        if (!hasAccess) {
          message.error('您没有权限访问此页面');
          navigate('/dashboard');
        }
      } else {
        console.log('[DynamicRouteGuard] 未找到路由配置，当前路径:', currentPath);
      }
    }
  }, [location.pathname, permissionData, dynamicRoutes, navigate]);

  if (permissionLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <Spin size="large" />
        <div>加载权限配置中...</div>
      </div>
    );
  }

  if (!isAuthenticated || !permissionData) {
    return (
      <Routes>
        {basicRoutes}
        {protectedRoutes}
      </Routes>
    );
  }

  console.log('[DynamicRouteGuard] 渲染路由配置:');
  console.log('- 基础路由: 已配置');
  console.log('- 动态路由数量:', dynamicRoutes.length);
  console.log('- 保护路由: 已配置');

  return (
    <Routes>
      {/* 基础路由 */}
      {basicRoutes}

      {/* 动态路由 */}
      {dynamicRoutes.map((route, index) => (
        <Route
          key={`dynamic-${index}`}
          path={route.path}
          element={
            <MainLayout>
              {route.element}
            </MainLayout>
          }
        />
      ))}

      {/* 静态保护路由 */}
      {protectedRoutes}

      {/* 404 路由 - 捕获所有未匹配的路由 */}
      <Route
        path="*"
        element={<NotFoundPage />}
      />
    </Routes>
  );
};

export default DynamicRouteGuard;